package com.qyb.controller;

import com.qyb.config.SpringWebSocketHandler;
import com.qyb.other.DocumentInfo;
import com.qyb.util.JsonUtils;
import com.qyb.util.ZxingDecoderHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.util.IdGenerator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.TextMessage;
import sun.misc.BASE64Decoder;

import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.Session;
import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * <p>
 * 实现功能：
 * <p/>
 *
 * @author 秦有宝
 * @version 1.0.00
 */
@Controller
@RequestMapping("scan")
public class ScanController {
    /**
     * 测试界面
     */
    @RequestMapping(value = "show")
    public String show(HttpServletRequest request) {
        return "main/ScanTest";
    }

    @Bean//这个注解会从Spring容器拿出Bean
    public SpringWebSocketHandler socketHandler() {
        return new SpringWebSocketHandler();
    }

    /**
     * 文件上传
     *
     * @param request request
     * @return 返回上传成功页面地址
     * @throws IllegalStateException IllegalStateException
     * @throws IOException           IOException
     */
    @ResponseBody
    @RequestMapping(value = "submitFile", method = RequestMethod.POST)
    public String myFile(HttpServletRequest request) throws IllegalStateException, IOException {
        long startTime = System.currentTimeMillis();
        Cookie[] cookies = request.getCookies();
        Cookie cooky1 = cookies[0];
        String cooky1Name = cooky1.getName();
        String cooky1Value = cooky1.getValue();
        Enumeration<String> headerNames = request.getHeaderNames();
        String fileName = request.getHeader("x_filename");
        String fileName1 = java.net.URLDecoder.decode(fileName, "UTF-8");
        String fileId = request.getHeader("X_FILEID");
        ServletInputStream servletInputStream = request.getInputStream();
        StringBuilder content = new StringBuilder();
        byte[] b = new byte[1024];
        int lens = -1;
        while ((lens = servletInputStream.read(b)) > 0) {
            content.append(new String(b, 0, lens));
        }
        String imgStr = content.toString();// 内容

//        base64ToImageFromCSEncode(imgStr,fileName1);
       String barCode = doSaveUploadFile(imgStr,fileName1);

        //获取UserId
        String userId = "123";
        /*if(cooky1Name.equals("UserToken")){
            if(cooky1Value.equals(Session.tocken)){
                userId = Session.userId;
           }
        }*/

        List<DocumentInfo> documentInfos = new ArrayList<>();
        DocumentInfo documentInfo = new DocumentInfo();
        documentInfo.setId("123");
        documentInfo.setFileName(fileName1);
        documentInfo.setDescription("我的测试");
        documentInfo.setBarCode(barCode);
        documentInfos.add(documentInfo);
        socketHandler().sendMessageToUser(userId, new TextMessage(JsonUtils.toJson(documentInfos)));

        /*MultiValueMap<String, MultipartFile> files = request.getMultiFileMap();
        List<String> docList = new ArrayList<String>();
        if (files != null) {
            for (List<MultipartFile> list : files.values()) {
                MultipartFile file = list.get(0);
                //一次遍历所有文件
                if (file != null && !file.isEmpty()) {
                    //保存上传文件
                    docList.add(doSaveUploadFile(file, request));
                }
            }
        }
        long endTime = System.currentTimeMillis();
        LOGGER.debug("文件上传耗时：" + String.valueOf(endTime - startTime) + "ms");*/
//        return JsonUtils.toJson(docList);


//        Response.Write(result);
       /* var fileStream = Request.InputStream;

        //没有传入文件名时，自动生成文件名
        var fileName = HttpUtility.UrlDecode(Request.Headers["X_FILENAME"]);
        if (string.IsNullOrEmpty(fileName))
        {
            return "file name is empty";
        }
        if (fileStream != null && fileStream.Length > 0)
        {
            //没有传入文件Id时，自动生成Id
            var fileIdStr = Request.Headers["X_FILEID"];
            var fileId = string.IsNullOrEmpty(fileIdStr) ? Guid.NewGuid() : Guid.Parse(fileIdStr);

            var docManager = DocumentManagerFactory.GetManager();
            var document = new Document(fileId, fileName, fileStream);
            var docInfo = docManager.UploadDocument(document);
            var serializer = new JavaScriptSerializer { MaxJsonLength = int.MaxValue };
            return serializer.Serialize(docInfo);
        }
        return "file is empty !";*/
        return "";
    }


    /**
     * 保存上传文件.
     * 子类重写
     *
     * @param imgStr 上传的文件
     */
    protected String doSaveUploadFile(final String imgStr, final String fileName) {
        BASE64Decoder decoder = new BASE64Decoder();
//        DocumentInfo documentInfo = null;
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            /*for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }*/
            // 生成jpeg图片
            InputStream inputStream = new ByteArrayInputStream(b);
            //解码
            String barCode = ZxingDecoderHandler.decode(inputStream);
            System.out.println("识别条形码：" + barCode);
            return barCode;
//            documentInfo = documentManager.uploadDocument(input, fileName);
//                return true;
        } catch (Exception e) {
//                LogUtil.addExceptionLog("文件上传失败", e);
        }
        /*return Objects.nonNull(documentInfo) ? documentInfo.getId() : null;*/
        return null;
    }

    /**
     * base64转图片并保存到本地
     * @param imgStr
     * @param fileName
     */
    public static void base64ToImageFromCSEncode(String imgStr,String fileName) {
        // base64字符串转化成图片
        // 对字节数组字符串进行Base64解码并生成图片
        String outputFileName = "E:/我的"+fileName+".jpg";
        if (imgStr == null) {
            // 图像数据为空
            //return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            /*for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }*/
            // 生成jpeg图片
            String imgFilePath = outputFileName;// 新生成的图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
//                return true;
        } catch (Exception e) {
//                return false;
        }
    }
    /// <summary>
    /// 结束扫描仪扫描
    /// </summary>
    /// <param name="cId"></param>
    /// <returns></returns>

  /*  public String completeScan(String cId)
    {
       *//* ScannerService.SetScanResults(cId,Request.Form);
        return new EmptyResult();*//*
    }*/
}
